package com.sansecy.video;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public abstract class VolumeBrightnessController extends FrameLayout {
    public static final float BRIGHT_MAX = 1.0F;
    public static final float BRIGHT_MIN = 0.01F;
    private final AudioManager mAudioManager;
    private final GestureDetector mGestureDetector;

    /**
     * 最大声音
     */
    private final int mMaxVolume;
    /**
     * 当前声音
     */
    private int mVolume = -1;
    /**
     * 当前亮度
     */
    private float mBrightness = -1f;
    private MyGestureListener mGestureListener;
    private GestureDetector.SimpleOnGestureListener mOnGestureListener;
    private Handler mHandler;
    private WindowManager mWindowManager;
    private Activity mActivity;
    private int mTouchSlop;
    private int mScrollDirection = -1;
    ;

    public void setOnGestureListener(GestureDetector.SimpleOnGestureListener onGestureListener) {
        mOnGestureListener = onGestureListener;
    }

    public VolumeBrightnessController(@NonNull Context context) {
        this(context, null);
    }

    public VolumeBrightnessController(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mActivity = (Activity) context;
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mGestureListener = new MyGestureListener();
        mGestureDetector = new GestureDetector(context, mGestureListener);
        mHandler = new Handler(Looper.getMainLooper());
        mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
    }

    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event)) {
            return true;
        }
        // 处理手势结束
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                endGesture();
                break;
        }
        return false;
    }

    /**
     * 手势结束
     */
    protected void endGesture() {
        mVolume = -1;
        mBrightness = -1f;
        mScrollDirection = -1;
        // 隐藏
        mDismissHandler.removeMessages(0);
        mDismissHandler.sendEmptyMessageDelayed(0, 500);
    }

    /**
     * 定时隐藏
     */
    private final Handler mDismissHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            onViewHide();
        }
    };

    /**
     * 滑动改变声音大小
     */
    private void onVolumeSlide(float percent) {
        if (mVolume == -1) {
            mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (mVolume < 0)
                mVolume = 0;
        }
        int index = (int) (percent * mMaxVolume) + mVolume;
        if (index > mMaxVolume)
            index = mMaxVolume;
        else if (index < 0)
            index = 0;

        // 变更声音
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);
        onVolumeChange(mMaxVolume, index);

    }

    private OnBrightnessChangeListener onBrightnessChangeListener;

    interface OnBrightnessChangeListener {
        void onBrightnessSlide(float percent);
    }

    public void setOnBrightnessChangeListener(OnBrightnessChangeListener onBrightnessChangeListener) {
        this.onBrightnessChangeListener = onBrightnessChangeListener;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return false;
    }

    /**
     * 滑动改变亮度
     */
    private void onBrightnessSlide(float percent) {
        if (onBrightnessChangeListener != null) {
            onBrightnessChangeListener.onBrightnessSlide(percent);
        }
        if (mBrightness < 0) {
            mBrightness = mActivity.getWindow().getAttributes().screenBrightness;
            if (mBrightness < 0) {
                mBrightness = getSystemBrightness() / 255f;
            }
            if (mBrightness <= 0.00f)
                mBrightness = 0.01f;
            if (mBrightness < 0.01f)
                mBrightness = 0.01f;
        }
        WindowManager.LayoutParams lpa = mActivity.getWindow().getAttributes();
        lpa.screenBrightness = mBrightness + percent;
        if (lpa.screenBrightness > BRIGHT_MAX)
            lpa.screenBrightness = BRIGHT_MAX;
        else if (lpa.screenBrightness < BRIGHT_MIN)
            lpa.screenBrightness = BRIGHT_MIN;
        mActivity.getWindow().setAttributes(lpa);
        onBrightnessChange(BRIGHT_MAX, lpa.screenBrightness);
    }

    private int getSystemBrightness() {
        int systemBrightness = 0;
        try {
            systemBrightness = Settings.System.getInt(mActivity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return systemBrightness;
    }

    private static final String TAG = "VolumeBrightnessControl-App";

    private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            return isEnabled();
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            if (mOnGestureListener != null) {
                return mOnGestureListener.onDoubleTapEvent(e);
            }
            return super.onDoubleTapEvent(e);
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (mOnGestureListener != null) {
                return mOnGestureListener.onSingleTapUp(e);
            }
            return super.onSingleTapUp(e);
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (mOnGestureListener != null) {
                return mOnGestureListener.onSingleTapConfirmed(e);
            }
            return super.onSingleTapConfirmed(e);
        }

        /**
         * 双击
         */
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (mOnGestureListener != null) {
                return mOnGestureListener.onDoubleTap(e);
            }
            return false;
        }

        /**
         * 滑动
         */
        @Override
        public boolean onScroll(MotionEvent downEvent, MotionEvent motionEvent,
                                float distanceX, float distanceY) {
            if (downEvent == null || motionEvent == null) {
                return false;
            }
            int downX = (int) downEvent.getX();
            int downY = (int) downEvent.getY();
            float oldX = downEvent.getX();
            float oldY = downEvent.getY();
            int windowWidth = getWidth();
            int windowHeight = getHeight();
            int x = (int) motionEvent.getX();
            int y = (int) motionEvent.getY();
            float deltaX = Math.abs(x - oldX);
            float deltaY = Math.abs(y - oldY);
            if (deltaX > mTouchSlop || deltaY > mTouchSlop) {
                if (mScrollDirection == -1) {
                    if (deltaX > deltaY) {
                        mScrollDirection = LinearLayout.HORIZONTAL;
                    } else if (deltaX < deltaY) {
                        mScrollDirection = LinearLayout.VERTICAL;
                    }
                }
                if (mScrollDirection == LinearLayout.VERTICAL) {
                    if (downY > getHeight() * 0.1 && downY < getHeight() * 0.9) {
                        if (oldX > windowWidth / 2f) {// 右边滑动
                            onVolumeSlide((oldY - y) / windowHeight);
                        } else if (oldX < windowWidth / 2f)// 左边滑动
                            onBrightnessSlide((oldY - y) / windowHeight);
                        return true;
                    }
                } else if (mScrollDirection == LinearLayout.HORIZONTAL) {
                    //横向滑动
                    if (deltaX > deltaY) {
                        if (oldX > getWidth() * 0.1 && oldX < getWidth() * 0.9) {
                            if (mOnProgressChangeListener != null) {
                                mOnProgressChangeListener.onProgressChange((int) ((x - oldX) / mTouchSlop * 1000));
                            }
                        }
                    }
                }
            }
            return false;
        }
    }

    private OnProgressChangeListener mOnProgressChangeListener;

    public void setOnProgressChangeListener(OnProgressChangeListener onProgressChangeListener) {
        mOnProgressChangeListener = onProgressChangeListener;
    }

    public interface OnProgressChangeListener {
        void onProgressChange(int progress);
    }

    protected void onProgressChange(int progress) {

    }

    protected void onVolumeChange(int maxVolume, int volume) {

    }

    protected void onBrightnessChange(float maxScreenBrightness, float screenBrightness) {

    }

    public void onProgressChange(float max, float progress) {

    }

    protected void onViewHide() {

    }
}
